package hn.cch.lettuce.service.impl;

import hn.cch.lettuce.LettuceApplication;
import hn.cch.lettuce.entity.ObjectEntity;
import hn.cch.lettuce.service.LettuceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LettuceServiceImpl implements LettuceService {

    private static final Logger logger = LoggerFactory.getLogger(LettuceServiceImpl.class);


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public ObjectEntity getObject(String key) {
        if (Objects.equals(redisTemplate.hasKey(key), Boolean.TRUE)) {
            ObjectEntity objectEntity = (ObjectEntity) redisTemplate.opsForValue().get(key);
            if (Objects.isNull(objectEntity)) {
                objectEntity = ObjectEntity.getObjectEntity();
            }
            return objectEntity;
        } else {
            ObjectEntity objectEntity = ObjectEntity.getObjectEntity();
            redisTemplate.opsForValue().set(key, objectEntity, 30L, TimeUnit.SECONDS);
            return objectEntity;
        }
    }

    public void testObjectEntity(String key, int count) {
        for (int i = 0; i < count; i++) {
            if (Objects.equals(redisTemplate.hasKey(key), Boolean.TRUE)) {
                ObjectEntity value = (ObjectEntity) redisTemplate.opsForValue().get(key);
                if (Objects.nonNull(value)) {
                    continue;
                }
            }
            redisTemplate.opsForValue().set(key, ObjectEntity.getObjectEntity());
            logger.info("set");
        }
    }

}
